package com.starhub.monitor.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.starhub.monitor.entity.AIChatLog;
import com.starhub.monitor.dto.ChatLogDetailDto;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Mapper
public interface AIChatLogMapper extends BaseMapper<AIChatLog> {
    
    /**
     * 获取今日请求总数
     * @param startOfDay 今天的开始时间
     * @return 请求总数
     */
    @Select("SELECT COUNT(*) FROM ai_chat_log WHERE request_time >= #{startOfDay}")
    Long countTodayRequests(@Param("startOfDay") LocalDateTime startOfDay);
    
    /**
     * 获取API调用总次数
     * @return API调用总次数
     */
    @Select("SELECT COUNT(*) FROM ai_chat_log")
    Long countTotalApiCalls();
    
    /**
     * 获取最近的用户对话活动日志
     * @param limit 限制返回记录数
     * @return 包含用户ID、状态、请求时间的活动记录列表
     */
    @Select("SELECT l.id, l.user_id, l.status, l.request_time, l.agent_id, l.error_message, " +
            "l.request_content, u.username, u.name " +
            "FROM ai_chat_log l " +
            "LEFT JOIN sys_user u ON l.user_id = u.id " +
            "ORDER BY l.request_time DESC " +
            "LIMIT #{limit}")
    List<Map<String, Object>> getRecentActivityLogs(@Param("limit") int limit);
    
    /**
     * 获取指定时间段内成功和失败的请求数量
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 包含成功/失败统计的Map
     */
    @Select("SELECT status, COUNT(*) as count FROM ai_chat_log " +
            "WHERE request_time >= #{startTime} AND request_time < #{endTime} " +
            "GROUP BY status")
    List<Map<String, Object>> countRequestsByStatusAndTimeRange(
            @Param("startTime") LocalDateTime startTime, 
            @Param("endTime") LocalDateTime endTime);
    
    /**
     * 获取指定时间段内成功的请求数量
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 成功请求数量
     */
    @Select("SELECT COUNT(*) FROM ai_chat_log " +
            "WHERE request_time >= #{startTime} AND request_time < #{endTime} " +
            "AND status = 1")
    Long countSuccessRequestsByTimeRange(
            @Param("startTime") LocalDateTime startTime, 
            @Param("endTime") LocalDateTime endTime);
    
    /**
     * 获取指定时间段内失败的请求数量（状态为0的记录）
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 失败请求数量
     */
    @Select("SELECT COUNT(*) FROM ai_chat_log " +
            "WHERE request_time >= #{startTime} AND request_time < #{endTime} " +
            "AND status = 0")
    Long countFailureRequestsByTimeRange(
            @Param("startTime") LocalDateTime startTime, 
            @Param("endTime") LocalDateTime endTime);
            
    /**
     * 获取指定时间段内告警的请求数量（状态为2的记录）
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 告警请求数量
     */
    @Select("SELECT COUNT(*) FROM ai_chat_log " +
            "WHERE request_time >= #{startTime} AND request_time < #{endTime} " +
            "AND status = 2")
    Long countAlertRequestsByTimeRange(
            @Param("startTime") LocalDateTime startTime, 
            @Param("endTime") LocalDateTime endTime);
            
    /**
     * 获取告警数量（状态为2的记录数量）
     * @return 告警数量
     */
    @Select("SELECT COUNT(*) FROM ai_chat_log WHERE status = 2")
    Long countTotalAlerts();
    
    /**
     * 获取错误数量（状态为0的记录数量）
     * @return 错误数量
     */
    @Select("SELECT COUNT(*) FROM ai_chat_log WHERE status = 0")
    Long countTotalErrors();
    
    /**
     * 获取正常数量（状态为1的记录数量）
     * @return 正常数量
     */
    @Select("SELECT COUNT(*) FROM ai_chat_log WHERE status = 1")
    Long countTotalNormals();
    
    /**
     * 获取智能体使用统计数据（联表查询agent_config获取名称）
     * @return 智能体使用统计数据
     */
    @Select("SELECT l.agent_id, a.name as agent_name, COUNT(*) as usage_count " +
            "FROM ai_chat_log l " +
            "JOIN agent_config a ON l.agent_id = a.id " +
            "WHERE a.delete_type = 0 " +
            "GROUP BY l.agent_id, a.name " +
            "ORDER BY usage_count DESC")
    List<Map<String, Object>> getAgentUsageStats();

    @Select("SELECT l.*, " +
            "u.username, " +
            "u.name as realName, " +
            "a.name as agentName " +
            "FROM ai_chat_log l USE INDEX (idx_request_time_status) " +
            "LEFT JOIN sys_user u ON l.user_id = u.id " +
            "LEFT JOIN agent_config a ON l.agent_id = a.id " +
            "WHERE (#{startTime} IS NULL OR l.request_time >= #{startTime}) " +
            "AND (#{endTime} IS NULL OR l.request_time < #{endTime}) " +
            "AND (#{status} IS NULL OR #{status} = -1 OR l.status = #{status}) " +
            "ORDER BY l.request_time DESC " +
            "LIMIT 1000")
    List<ChatLogDetailDto> getChatLogDetails(@Param("startTime") LocalDateTime startTime,
                                           @Param("endTime") LocalDateTime endTime,
                                           @Param("status") Integer status);
} 